import { requireAuth } from '~/server/utils/auth'
import LikeService from '~/server/database/services/likeService'

export default defineEventHandler(async (event) => {
  try {
    // 验证用户身份
    const user = await requireAuth(event)
    
    // 获取请求体
    const body = await readBody(event)
    const { targetType, targetId } = body

    // 验证必填字段
    if (!targetType || !targetId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '目标类型和目标ID不能为空' }
      })
    }

    if (!['post', 'comment'].includes(targetType)) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '目标类型必须是post或comment' }
      })
    }

    // 切换点赞状态
    const result = await LikeService.toggleLike(
      user.id,
      targetType as 'post' | 'comment',
      parseInt(targetId)
    )

    return {
      success: true,
      data: result,
      message: result.liked ? '点赞成功' : '取消点赞成功'
    }
  } catch (error: unknown) {
    console.error('切换点赞状态失败:', error)
    
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      data: { message: '切换点赞状态失败' }
    })
  }
})
